package com.autohammal.task;

import java.util.Collections;
import java.util.List;
import com.autohammal.ITask;
import com.autohammal.TaskListener;
import com.autohammal.exception.handler.TaskExceptionHandler;

public class TaskContainer extends Task {
	private static final long serialVersionUID = 6959854128726240963L;
	private List<ITask> taskList = null;
	private TaskExceptionHandler taskExceptionHandler = null;

	public TaskContainer() {
		taskList = new java.util.concurrent.CopyOnWriteArrayList<ITask>();
	}

	public TaskContainer(TaskExceptionHandler taskExceptionHandler) {
		this();
		this.taskExceptionHandler = taskExceptionHandler;
	}

	public void combine(ITask... iTasks) {
		if (iTasks != null) {
			Collections.addAll(taskList, iTasks);
		}
	}

	@Override
	public void executeTask() {
		for (ITask task : taskList) {
			try {
				TaskListener tl = task.getTaskListener();
				if (tl != null)
					tl.onTaskBefore();
				task.executeTask();
				if (tl != null)
					tl.onTaskAfter();
				task.setTaskStatus(TaskStatus.COMPLETE);
			} catch (Exception e) {
				if (taskExceptionHandler != null) {
					taskExceptionHandler.setExceptionTask(task);
					taskExceptionHandler.handler(e);
				}
			}
		}
	}

	public void setTaskExceptionHandler(
			TaskExceptionHandler taskExceptionHandler) {
		this.taskExceptionHandler = taskExceptionHandler;
	}

	@Override
	public String getTaskName() {
		StringBuffer sb = new StringBuffer();
		for (ITask task : taskList) {
			sb.append(task.getTaskName());
			sb.append(",");
		}
		if (taskList.size() > 0)
			sb.substring(0, sb.length() - 1);
		return "Combine Task[" + sb + "]";
	}

	@Override
	public String getTaskId() {
		return "TN_" + getTaskName();
	}

}
